from django.db import models

STATUS = (
    (0, 'STANDBY'),
    (1, 'EXECUTING'),
    (2, 'COMPLETE'),
    (3, 'BROKEN'),
    (4, 'STALLED'),
    (5, 'ABORTED'),
    (6, 'INACTIVE'),
)

class Source(models.Model):
    """
    element - amount of elements retrieved on average on last 3 runs 
    interval - every 3 hours
    """
    name = models.CharField(max_length=50)
    site = models.CharField(max_length=50)
    status = models.IntegerField(choices=STATUS, default=0)
    last = models.ForeignKey('Log', related_name='last_log', null=True, blank=True)
    elements = models.IntegerField(default=20)
    interval = models.IntegerField(default=3)

    class Meta:
        ordering = ('name',)
        app_label = 'feedreader'

    def __unicode__(self):
        return self.name

class Log(models.Model):
    timestamp = models.DateTimeField()
    time = models.IntegerField(null=True, blank=True)
    source = models.ForeignKey(Source, related_name='logs')
    status = models.IntegerField(choices=STATUS, default=0)
    items = models.IntegerField(default=0, null=True, blank=True)
    buffer = models.IntegerField(default=None, null=True, blank=True)

    def delete(self):
        """Deataches itself from log's source before deleting"""
        self.source.last = None
        self.source.save()
        super(Log, self).delete()

    class Meta:
        ordering = ('-time',)
        app_label = 'feedreader'

    def __unicode__(self):
        return '%s (%s, %s)' % (self.source.name, self.timestamp, self.status)


class Chunk(models.Model):
    time = models.DateTimeField()
    log = models.ForeignKey(Log, related_name='chunks')
    url = models.CharField(max_length=100)
    size = models.IntegerField()
    status = models.IntegerField(choices=STATUS, default=0)

    class Meta:
        ordering = ('-time',)
        app_label = 'feedreader'

    def __unicode__(self):
        return '%s (%s, %s)' % (self.log.source.name, self.time, self.size)

    